package com.wenkang.stu.config.security;

import com.wenkang.stu.pojo.SysMenu;
import com.wenkang.stu.pojo.SysRole;
import com.wenkang.stu.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;


/**
 * 根据当前url获取所需访问权限
 */
@Component
public class SecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private SysMenuService menuService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        // 1、获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        // 2、获取所有菜单(包含对应角色)
        List<SysMenu> menus = menuService.selectMenusWithRole();
        // 3、获取当前请求所需角色
        for (SysMenu menu : menus) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                String[] collect = menu.getRoleList().stream().map(SysRole::getRoleName).toArray(String[]::new);
                return SecurityConfig.createList(collect);
            }
        }
        // 4、返回角色
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
